<template>
  <el-card class="box-card">
    <!-- 卡片顶部添加品牌按钮 -->
    <el-button
      type="primary"
      size="default"
      icon="Plus"
      @click="addTrademark"
      v-if="useStore.buttons.includes('btn.Trademark.add')"
      >添加品牌</el-button
    >
    <!-- 表组件,用于展示已有平台数据 -->
    <!-- 
           table
           --border:可以设置表格纵向是否有边框
           table-column
           --label:某一个列表
           --width:设置这列宽度
           --align:设置这一列对齐方式
         -->
    <el-table style="margin-top: 10px" border :data="trademarkArr">
      <el-table-column
        label="序号"
        width="80"
        align="center"
        type="index"
      ></el-table-column>

      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>

          <el-popconfirm
            :title="`你确定要删除这个品牌吗？`"
            width="250"
            icon="delete"
            @confirm="removeTradeMark"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 
        pagination
        v-model:current-page:设置分页器当前页码
        v-model:page-size:设置每一页展示数据条数
        page-sizes:用于设置下拉菜单数据
        background:设置分页器按钮的背景颜色
        layout:可以设置分页器六个子组件的位置
      -->
    <el-pagination
      @current-change="changePageNo"
      @size-change="sizeChange"
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total "
      :total="total"
    />
  </el-card>

  <!-- 对话框组件:在添加品牌与修改已有品牌 -->
  <!-- v-model:属性用户控制对话框的显示与隐藏true 显示,false隐藏 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      style="width: 80%"
      :model="trademarkParams"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="品牌名称" label-width="80px" prop="tmName">
        <el-input
          placeholder="请输入你的品牌名称"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
        <!-- 
          upload组件的属性
          action图片上传路径书写/api

         -->

        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 具名插槽 -->
    <template #footer>
      <el-button type="parimary" size="default" @click="cancel">取消</el-button>
      <el-button type="parimary" size="default" @click="confirm"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// 引入组合式API函数ref
import { ref, onMounted, reactive } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from "@/api/product/trademark/type";

// 按钮权限的实现
import useUserStore from "@/store/modules/user";
// 获取用户相关的仓库
let userStore = useUserStore();

// 当前页面
let pageNo = ref(<number>1);
// 每一页展示多少条数据
let limit = ref(<number>3);
// 存储已有品牌数据总数
let total = ref<number>(0);
// 储存已有品牌的数据
let trademarkArr = ref<Records>([]);
// 控制对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false);
// 定义新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});

// 获取el-form的组件实列
let formRef = ref();

// 添加品牌
const addTrademark = () => {
  console.log("aaaa");

  //对话框显示
  dialogFormVisible.value = true;
  // 收集数据清空
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";

  formRef.value?.clearValidate("tmName");
  formRef.value?.clearValidate("logoUrl");
};
// 修改品牌按钮的回调
const updateTrademark = (row: any) => {
  dialogFormVisible.value = true;
  //ES6语法合并对象
  Object.assign(trademarkParams, row);

  // 回填已有品牌的数据
  // trademarkParams.id = row.id;
  // trademarkParams.tmName = row.tmName;
  // trademarkParams.logoUrl = row.logoUrl;

  formRef.value?.clearValidate("tmName");
  formRef.value?.clearValidate("logoUrl");
};
// 对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false;
};
//对话框底部确定按钮
const confirm = async () => {
  //在你发请求之前,对整个表单进行校验
  formRef.value.validate(async (valid: any) => {
    if (!valid) return;

    let result: any = await reqAddOrUpdateTrademark(trademarkParams);
    console.log(result);
    // 添加|| 修改品牌成功
    if (result.code == 200) {
      // 关闭对话框
      dialogFormVisible.value = false;
      // 弹出提示信息
      ElMessage({
        type: "success",
        message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功",
      });
      // 再次发请求获取已有全部品牌的信息
      getHasTrademark(trademarkParams.id ? pageNo.value : 1);
    } else {
      // 添加品牌失败
      ElMessage({
        type: "error",
        message: trademarkParams.id ? "修改品牌失败" : "添加品牌失败",
      });
      dialogFormVisible.value = false;
    }
  });
};

// 获取已有品牌的接口封装为一个函数,在任何清空下向获取数据,调用函数即可
const getHasTrademark = async () => {
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  );
  if (result.code == 200) {
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
};

// 组件挂载完毕钩子,发一次请求,获取第一页,
onMounted(() => {
  getHasTrademark();
});

// 分页器当前页面发生变化的时候会触发
// 对应当前页面发送变化自定义事件，组件
const changePageNo = () => {
  // 当前页面发生变化的时候,再次发送请求获取数据
  getHasTrademark();
};

// 当下拉菜单发送变化触发该方法
const sizeChange = () => {
  pageNo.value = 1;
  getHasTrademark();
};

// 图片上传之前的触发的构造函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 构造市在图片上传之前触发,上传文件之前可以约束文件类型与大小
  // 要去上传文件格式png|JPG|gif 4M
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpge" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage.error("上传的文件大小必须小于4M");
      return false;
    }
  } else {
    ElMessage.error("上传文件格式务必为PNG|JPG|GIF");
    return false;
  }
};

// 图片上传成功的钩子函数

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
) => {
  trademarkParams.logoUrl = response.data;
  // 图片上传成功,清除掉对应的图片校验结果
  formRef.value.clearValidate("logoUrl");
};

// 品牌自定义校验规则的方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  // 自定义校验规则
  if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error("品牌名称位数大于等于两位"));
  }
};

// 品牌logo自定义校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  // 如果图片上传
  if (value) {
    callBack();
  } else {
    callBack(new Error("LOGO图片务必上传"));
  }
};

// 表单校验规则对象
const rules = {
  tmName: [
    // required,这个字段务必校验,
    //trigger:代表触发表单校验规则blur,change
    { required: true, trigger: "blur", validator: validatorTmName },
  ],
  logoUrl: [{ required: true, trigger: "blur", validator: validatorLogoUrl }],
};

// 删除品牌数据
const removeTradeMark = async (id: number) => {
  // 点击确定按钮删除已有品牌请求

  let result = await reqDeleteTrademark(id);

  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    getHasTrademark();
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
